package com.ayf.payment.game.api.service.payment.ayb;

import com.alibaba.fastjson.JSONObject;
import com.ayf.payment.game.api.channel.alipay.internal.util.StringUtils;
import com.ayf.payment.game.api.dto.ayb.MerchantTwoDTO;
import com.ayf.payment.game.api.dto.ayb.SignPayProductDTO;
import com.ayf.payment.game.api.dto.platform.PaymentChannelDTO;
import com.ayf.payment.game.api.httpclient.HttpUtils;
import com.ayf.payment.game.api.service.SignPayProductService;
import com.ayf.payment.game.api.type.CharSetEnum;
import com.ayf.payment.game.api.utils.CommonResult;
import com.ayf.payment.game.api.utils.SM2Utils;
import com.swwx.charm.commons.lang.utils.LogPortal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.LinkedHashMap;
import java.util.Map;
@Service
public class MerchantTwoService {

    @Autowired
    private SignPayProductService signPayProductService;


    private final String MERCHANT_APPLY_URL="/ayb-pay-api/v1/merchant/merchant_two_apply";

    private final String MERCHANT_MODIFY_URL="/ayb-pay-api/v1/merchant/merchant_two_modify";

    private final String MERCHANT_QUERY="/ayb-pay-api/v1/merchant/merchant_two_query";

    private final String MERCHANT_UPDATA_SUPER="/ayb-pay-api/v1/merchant/merchant_two_updata_super";


    public CommonResult apply(SignPayProductDTO dto, String traceId,PaymentChannelDTO channel){

        CommonResult commonResult=new CommonResult();
        commonResult.setCode(-1);
        commonResult.setMsg("数据提交异常，错误码："+traceId);

        SignPayProductDTO signPayProduct=signPayProductService.getSignPayProductDTOByMId(dto.getMerchantId(),channel.getCode());
        MerchantTwoDTO merchantTwoDTO=dto.getMerchantTwoDTO();
        if(signPayProduct.getPayProductNum()==0){
            commonResult.setCode(-1);
            commonResult.setMsg("没有提供相关产品");
        }
        if(signPayProduct==null || signPayProduct.getCountSignPayProduct()==0){  //第一次提交数据
            signPayProduct=new SignPayProductDTO();
            signPayProduct.setMerchantId(dto.getMerchantId());
            signPayProduct.setPayCode("AYB_PAY");
            signPayProduct.setApplyStatus(0);
            signPayProduct.setMerchantTwoDTO(merchantTwoDTO);
            int sppId =signPayProductService.insertSignPayProduct(signPayProduct);
            signPayProduct.setId(sppId);
            commonResult=apply(merchantTwoDTO,traceId, channel);
            JSONObject json=(JSONObject)commonResult.getData();
            switch(commonResult.getCode()){
                case 200:
                    signPayProduct.setChannelMerchantId(json.getString("mid"));
                    if(json.get("status")!=null && json.get("status").equals("2")){
                        signPayProduct.setApplyStatus(2);
                        signPayProduct.setUpdateStatus(2);
                    }else{
                        signPayProduct.setApplyStatus(1);
                        signPayProduct.setUpdateStatus(1);
                    }
                    signPayProduct.setFailMsg("-");
                    commonResult.setMsg(json.getString("msgData"));
                    break;
                case 201:
                    signPayProduct.setChannelMerchantId(json.getString("mid"));
                    signPayProduct.setApplyStatus(-1);
                    signPayProduct.setUpdateStatus(-1);
                    signPayProduct.setFailMsg(json.getString("msgData"));
                    commonResult.setMsg(json.getString("msgData"));
                    break;
                case 202:  //重复提交
                    commonResult.setMsg(commonResult.getMsg());
                    break;
                default:
                    signPayProduct.setApplyStatus(-1);
                    signPayProduct.setUpdateStatus(-1);
                    signPayProduct.setFailMsg(commonResult.getMsg());
                    commonResult.setMsg(commonResult.getMsg());
            }
            signPayProductService.updateSignPayProduct(signPayProduct);

        }else{     //重新提交
            signPayProduct.setMerchantTwoDTO(merchantTwoDTO);
            if(signPayProduct.getChannelMerchantId()!=null){
                merchantTwoDTO.setChannelMerchantId(signPayProduct.getChannelMerchantId());
                commonResult=modify(merchantTwoDTO,traceId,channel);
                JSONObject json=(JSONObject)commonResult.getData();
                switch(commonResult.getCode()){
                    case 200:   //提交成功
                        if(json.get("status")!=null && json.get("status").equals("2")){
                            signPayProduct.setApplyStatus(2);
                            signPayProduct.setUpdateStatus(2);
                        }else{
                            signPayProduct.setApplyStatus(1);
                            signPayProduct.setUpdateStatus(1);
                        }
                        signPayProduct.setFailMsg("-");
                        commonResult.setMsg(json.getString("msgData"));
                        break;
                    case 201:  //数据错误
                        if(!(json.get("status")!=null && json.get("status").equals("2"))){
                            signPayProduct.setApplyStatus(-1);
                        }
                        signPayProduct.setUpdateStatus(-1);
                        signPayProduct.setFailMsg(json.getString("msgData"));
                        commonResult.setMsg(json.getString("msgData"));
                        break;
                    case 202:  //重复提交
                        commonResult.setMsg(commonResult.getMsg());
                        break;
                    default:
                        signPayProduct.setApplyStatus(-1);
                        signPayProduct.setUpdateStatus(-1);
                        signPayProduct.setFailMsg(commonResult.getMsg());
                        commonResult.setMsg(commonResult.getMsg());
                }
                signPayProductService.updateSignPayProduct(signPayProduct);
            }else{
                commonResult=apply(merchantTwoDTO,traceId,channel);
                JSONObject json=(JSONObject)commonResult.getData();
                switch(commonResult.getCode()){
                    case 200:
                        signPayProduct.setChannelMerchantId(json.getString("mid"));
                        if(json.get("status")!=null && json.get("status").equals("2")){
                            signPayProduct.setApplyStatus(2);
                            signPayProduct.setUpdateStatus(2);
                        }else{
                            signPayProduct.setApplyStatus(1);
                            signPayProduct.setUpdateStatus(1);
                        }
                        signPayProduct.setFailMsg("-");
                        commonResult.setMsg(json.getString("msgData"));
                        break;
                    case 201:
                        signPayProduct.setChannelMerchantId(json.getString("mid"));
                        if(!(json.get("status")!=null && json.get("status").equals("2"))){
                            signPayProduct.setApplyStatus(-1);
                        }
                        signPayProduct.setUpdateStatus(-1);
                        signPayProduct.setFailMsg(json.getString("msgData"));
                        commonResult.setMsg(json.getString("msgData"));
                        break;
                    case 202:  //重复提交
                        commonResult.setMsg(commonResult.getMsg());
                        break;
                    default:
                        signPayProduct.setApplyStatus(-1);
                        signPayProduct.setUpdateStatus(-1);
                        signPayProduct.setFailMsg(commonResult.getMsg());
                        commonResult.setMsg(commonResult.getMsg());
                }
                signPayProductService.updateSignPayProduct(signPayProduct);
            }
        }
       return commonResult;
    }
    private CommonResult apply(MerchantTwoDTO merchantTwoDTO,String traceId,PaymentChannelDTO paymentChannelDTO){
        Map<String, String> reqParam = new LinkedHashMap<>();
        reqParam.put("merId",paymentChannelDTO.getAccountNumber());
        reqParam.put("signedName",merchantTwoDTO.getSignedName());
        reqParam.put("zzLegalPersonIdNo",merchantTwoDTO.getZzLegalPersonIdNo());
        reqParam.put("phone",merchantTwoDTO.getPhone());
        reqParam.put("profession",merchantTwoDTO.getProfession());
        reqParam.put("businessAddressProvince",merchantTwoDTO.getBusinessAddressProvince());
        reqParam.put("businessAddressCity",merchantTwoDTO.getBusinessAddressCity());
        reqParam.put("businessAddressArea",merchantTwoDTO.getBusinessAddressArea());
        reqParam.put("businessAddress",merchantTwoDTO.getBusinessAddress());
        reqParam.put("accountName",merchantTwoDTO.getAccountName());
        reqParam.put("bankCardNo",merchantTwoDTO.getBankCardNo());
        reqParam.put("provinceCode",merchantTwoDTO.getProvinceCode());
        reqParam.put("cityCode",merchantTwoDTO.getCityCode());

        reqParam.put("legalIdCardProsOriginalFilename",merchantTwoDTO.getLegalIdCardProsOriginalFilename());
        reqParam.put("legalIdCardConsOriginalFilename",merchantTwoDTO.getLegalIdCardConsOriginalFilename());
        reqParam.put("legalPersonBankCardOriginalFilename",merchantTwoDTO.getLegalPersonBankCardOriginalFilename());
        StringBuffer signBuffer = new StringBuffer();
        reqParam.forEach((key, value)->{
            signBuffer.append(key.concat("=")).append(value).append("&");
        });
        String signStr= SM2Utils.sign(paymentChannelDTO.getPlatformPrivateKey(),signBuffer.toString().concat("key=")+paymentChannelDTO.getChannelKey());
        LogPortal.info("{} 二级商户入网申请提交数据:{} 加密数据[{}] 正面{} 背面{} 卡面{}", traceId, signBuffer, signStr,merchantTwoDTO.getLegalIdCardProsFileByte().length(),merchantTwoDTO.getLegalIdCardConsFileByte().length(),merchantTwoDTO.getLegalPersonBankCardFileByte().length());
        reqParam.put("sign",signStr);
        reqParam.put("traceId",traceId);
        reqParam.put("legalIdCardProsFileByte",merchantTwoDTO.getLegalIdCardProsFileByte());
        reqParam.put("legalIdCardConsFileByte",merchantTwoDTO.getLegalIdCardConsFileByte());
        reqParam.put("legalPersonBankCardFileByte",merchantTwoDTO.getLegalPersonBankCardFileByte());

        CommonResult commonResult= HttpUtils.sendPostFormAyb(traceId,"二级商户入网申请",paymentChannelDTO.getPaymentUrl().concat(MERCHANT_APPLY_URL),reqParam, CharSetEnum.utf8);
        return commonResult;
    }

    private CommonResult modify(MerchantTwoDTO merchantTwoDTO,String traceId,PaymentChannelDTO paymentChannelDTO){
        Map<String, String> reqParam = new LinkedHashMap<>();
        reqParam.put("merId",paymentChannelDTO.getAccountNumber());
        reqParam.put("merchantId",merchantTwoDTO.getChannelMerchantId());
        reqParam.put("signedName",merchantTwoDTO.getSignedName());
        reqParam.put("zzLegalPersonIdNo",merchantTwoDTO.getZzLegalPersonIdNo());
        reqParam.put("phone",merchantTwoDTO.getPhone());
        reqParam.put("profession",merchantTwoDTO.getProfession());
        reqParam.put("businessAddressProvince",merchantTwoDTO.getBusinessAddressProvince());
        reqParam.put("businessAddressCity",merchantTwoDTO.getBusinessAddressCity());
        reqParam.put("businessAddressArea",merchantTwoDTO.getBusinessAddressArea());
        reqParam.put("businessAddress",merchantTwoDTO.getBusinessAddress());
        reqParam.put("accountName",merchantTwoDTO.getAccountName());
        reqParam.put("bankCardNo",merchantTwoDTO.getBankCardNo());
        reqParam.put("provinceCode",merchantTwoDTO.getProvinceCode());
        reqParam.put("cityCode",merchantTwoDTO.getCityCode());
        reqParam.put("legalIdCardProsOriginalFilename",merchantTwoDTO.getLegalIdCardProsOriginalFilename());
        reqParam.put("legalIdCardConsOriginalFilename",merchantTwoDTO.getLegalIdCardConsOriginalFilename());
        reqParam.put("legalPersonBankCardOriginalFilename",merchantTwoDTO.getLegalPersonBankCardOriginalFilename());
        StringBuffer signBuffer = new StringBuffer();
        reqParam.forEach((key, value)->{
            signBuffer.append(key.concat("=")).append(value).append("&");
        });
        String signStr= SM2Utils.sign(paymentChannelDTO.getPlatformPrivateKey(),signBuffer.toString().concat("key=")+paymentChannelDTO.getChannelKey());
       // LogPortal.info("{} 二级商户入网修改提交数据:{} 加密数据[{}] 正面{} 背面{} 卡面{}", traceId, reqParam, signStr,merchantTwoDTO.getLegalIdCardProsFileByte().length(),merchantTwoDTO.getLegalIdCardConsFileByte().length(),merchantTwoDTO.getLegalPersonBankCardFileByte().length());
        reqParam.put("legalIdCardProsFileByte",merchantTwoDTO.getLegalIdCardProsFileByte());
        reqParam.put("legalIdCardConsFileByte",merchantTwoDTO.getLegalIdCardConsFileByte());
        reqParam.put("legalPersonBankCardFileByte",merchantTwoDTO.getLegalPersonBankCardFileByte());
        reqParam.put("sign",signStr);
        reqParam.put("traceId",traceId);
        CommonResult commonResult= HttpUtils.sendPostFormAyb(traceId,"二级商户入网修改",paymentChannelDTO.getPaymentUrl().concat(MERCHANT_MODIFY_URL),reqParam, CharSetEnum.utf8);
        return commonResult;
    }

    public CommonResult merchantQurey(Integer merchantId, String traceId ,PaymentChannelDTO paymentChannel){
        SignPayProductDTO signPayProduct=signPayProductService.getSignPayProductDTOByMId(merchantId, paymentChannel.getCode());
        if(StringUtils.isEmpty(signPayProduct.getChannelMerchantId())){
            return new CommonResult(-1,"请完善提交信息！","");
        }
        Map<String, String> reqParam = new LinkedHashMap<>();
        reqParam.put("merId",paymentChannel.getAccountNumber());
        reqParam.put("merchantId",signPayProduct.getChannelMerchantId());
        StringBuffer signBuffer = new StringBuffer();
        reqParam.forEach((key, value)->{
            signBuffer.append(key.concat("=")).append(value).append("&");
        });
        String signStr= SM2Utils.sign(paymentChannel.getPlatformPrivateKey(),signBuffer.toString().concat("key=")+paymentChannel.getChannelKey());
        reqParam.put("sign",signStr);
        reqParam.put("traceId",traceId);
        LogPortal.info("{} 二级商户入网查询提交数据:{} 加密数据[{}]", traceId, reqParam, signStr);
        CommonResult commonResult= HttpUtils.sendPostFormAyb(traceId,"二级商户入网查询",paymentChannel.getPaymentUrl().concat(MERCHANT_QUERY),reqParam, CharSetEnum.utf8);
        LogPortal.info("{} 二级商户入网查询返回数据:{}", traceId, commonResult);
        if(commonResult.getCode()==200){
            if(commonResult.getData().toString().equals("SUCCESS") || commonResult.getData().toString().equals("PASS")){
                signPayProduct.setApplyStatus(2);
                signPayProduct.setFailMsg(commonResult.getMsg());
                signPayProductService.updateSignPayProduct(signPayProduct);
                commonResult.setMsg("入网成功");
            }else{
                if(commonResult.getData().toString().equals("REFUSE") || commonResult.getData().toString().equals("NO_PASS")){
                    signPayProduct.setApplyStatus(-1);
                    signPayProduct.setFailMsg(commonResult.getMsg());
                    signPayProductService.updateSignPayProduct(signPayProduct);
                    commonResult.setMsg("审核失败");
                }else{
                    signPayProduct.setFailMsg(commonResult.getMsg());
                    signPayProductService.updateSignPayProduct(signPayProduct);
                    commonResult.setMsg("入网审核中");
                }
            }
        }
        return commonResult;
    }

    public CommonResult merchantTwoUpdateSuper(Integer merchantId, String traceId,PaymentChannelDTO paymentChannel){
        SignPayProductDTO signPayProduct=signPayProductService.getSignPayProductDTOByMId(merchantId,paymentChannel.getCode());
        CommonResult commonResult=new CommonResult();
        if(StringUtils.isEmpty(signPayProduct.getChannelMerchantId())){
            signPayProductService.deleteByMerchantIdAndCode(merchantId,paymentChannel.getCode());
            commonResult.setCode(200);
            commonResult.setMsg("解约成功");
            return commonResult;
        }
        Map<String, String> reqParam = new LinkedHashMap<>();
        reqParam.put("merId",paymentChannel.getAccountNumber());
        reqParam.put("merchantId",signPayProduct.getChannelMerchantId());
        StringBuffer signBuffer = new StringBuffer();
        reqParam.forEach((key, value)->{
            signBuffer.append(key.concat("=")).append(value).append("&");
        });
        String signStr= SM2Utils.sign(paymentChannel.getPlatformPrivateKey(),signBuffer.toString().concat("key=")+paymentChannel.getChannelKey());
        reqParam.put("sign",signStr);
        reqParam.put("traceId",traceId);
        LogPortal.info("{} 二级商户入网解约提交数据:{} 加密数据[{}]", traceId, reqParam, signStr);
        commonResult= HttpUtils.sendPostFormAyb(traceId,"二级商户入网解约",paymentChannel.getPaymentUrl().concat(MERCHANT_UPDATA_SUPER),reqParam, CharSetEnum.utf8);
        LogPortal.info("{} 二级商户入网解约返回数据:{} ", traceId, reqParam);
        if(commonResult.getCode()==200){
            commonResult.setMsg(commonResult.getMsg());
            signPayProductService.deleteByMerchantIdAndCode(merchantId,paymentChannel.getCode());
        }else{
            commonResult.setMsg("解约失败！");
        }
        return commonResult;
    }
}
